package com.simple.core.config.mdc;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import org.slf4j.MDC;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author FanXing
 * @date 2023年02月05日 18:05
 */
public class LogMdcFilter extends OncePerRequestFilter {
    private final String responseHeader;
    private final String mdcTokenKey;
    private final String requestHeader;

    public LogMdcFilter(String responseHeader, String mdcTokenKey, String requestHeader) {
        this.responseHeader = responseHeader;
        this.mdcTokenKey = mdcTokenKey;
        this.requestHeader = requestHeader;
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        try {
            final String token;
            if (!StrUtil.isEmpty(requestHeader) && !StrUtil.isEmpty(request.getHeader(requestHeader))) {
                token = request.getHeader(requestHeader);
            } else {
                token = IdUtil.fastSimpleUUID();
            }
            MDC.put(mdcTokenKey, token);
            if (!StrUtil.isEmpty(responseHeader)) {
                response.addHeader(responseHeader, token);
            }
            filterChain.doFilter(request, response);
        } finally {
            MDC.remove(mdcTokenKey);
        }
    }
}
